import { Card, Form, Input, Button, Checkbox, message } from 'antd';
import styles from './index.module.scss';

import logo from '@/assets/images/logo.png';
import { useDispatch } from 'react-redux';
import { login } from '@/store/actions';
// import { useHistory } from 'react-router-dom/cjs/react-router-dom.min';
import { useHistory, useLocation } from 'react-router';

const Login = () => {
  const dispatch = useDispatch();
  const history = useHistory();
  const location = useLocation();
  // 登陆
  const onFinish = async values => {
    try {
      await dispatch(
        login({
          mobile: values.mobile,
          code: values.code,
        })
      );

      // 登陆成功1秒后跳转首页
      message.success('登陆成功', 1, () => {
        // 重定向到登陆前的页面
        history.replace(location.state?.from ?? '/home');
      });
    } catch (e) {
      // ?? 判断左侧是否为 undefined或者 null ，如果是，返回右侧
      message.warning(e.response?.data.message ?? '好像出错了');
    }
  };
  return (
    <div className={styles.root}>
      <div className="login-warrap">
        <Card bordered={false}>
          <img className="login-logo" src={logo} alt="logo" />
          <Form
            size="large"
            validateTrigger={['onBlur', 'onChange']}
            onFinish={onFinish}
            initialValues={{
              mobile: '16722222222',
              code: '246810',
              rember: true,
            }}
          >
            <Form.Item
              name="mobile"
              rules={[
                { required: true, message: '请输入手机号' },
                {
                  pattern: /^1[3-9]\d{9}$/,
                  message: '手机号格式不正确',
                  validateTrigger: 'onBlur',
                },
              ]}
            >
              <Input maxLength={11} placeholder="请输入手机号" />
            </Form.Item>

            <Form.Item
              name="code"
              rules={[
                { required: true, message: '请输入验证码' },
                {
                  len: 6,
                  message: '验证码格式不正确',
                  validateTrigger: 'onBlur',
                },
              ]}
            >
              <Input maxLength={6} placeholder="请输入验证码" />
            </Form.Item>

            <Form.Item name="rember" valuePropName="checked">
              <Checkbox>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
            </Form.Item>

            <Form.Item style={{ marginBotton: 0 }}>
              <Button type="primary" htmlType="submit" block>
                登陆
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    </div>
  );
};

export default Login;
